﻿using JuCheap.Core.Infrastructure;
using JuCheap.Core.Infrastructure.Exceptions;
using JuCheap.Core.Infrastructure.Extentions;
using JuCheap.Core.Infrastructure.Utilities;
using JuCheap.Core.IService;
using JuCheap.Core.IService.AppService;
using JuCheap.Core.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JuCheap.Core.WebApi.Controllers
{
    /// <summary>
    /// 菜单服务api
    /// </summary>
    [Route("api/[controller]")]
    public class MenuController : BaseApiController
    {
        private readonly ISysMenuService _sysMenuService;
        private readonly IMenuService _menuService;
        private readonly ICurrentUserService _currentUserService;
        private readonly bool _canEditOrDeleteMenu;

        /// <summary>
        /// ctor
        /// </summary>
        public MenuController(ISysMenuService sysMenuService, IMenuService menuService, IConfiguration configuration,
            ICurrentUserService currentUserService)
        {
            _sysMenuService = sysMenuService;
            _menuService = menuService;
            _currentUserService = currentUserService;
            _canEditOrDeleteMenu = configuration.GetValue<bool>("CanEditOrDeleteMenu");
        }

        /// <summary>
        /// 创建菜单信息
        /// </summary>
        /// <param name="menuReq"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("create")]
        public async Task<ActionResult<string>> Create([FromBody]MenuCreateRequestDto menuReq)
        {
            menuReq.ParentId = menuReq.ParentId.IsBlank() ? string.Empty : menuReq.ParentId;
            menuReq.Remark = menuReq.Remark.IsBlank() ? string.Empty : menuReq.Remark;
            menuReq.Icon = menuReq.Icon.IsBlank() ? "right" : menuReq.Icon;
            var menuId = await _menuService.CreateAsync(menuReq);
            return Ok(menuId);
        }

        /// <summary>
        /// 分页获取菜单信息
        /// </summary>
        [HttpPost]
        [Route("search")]
        public async Task<ActionResult<PagedResult<SysMenuDto>>> Search([FromBody]SysMenuFilter filter)
        {
            var menuList = await _menuService.GetMenuTableTreeAsync(filter);
            var records = new PagedResult<SysMenuDto>()
            {
                PageIndex = filter.PageIndex,
                PageSize = filter.PageSize,
                Datas = menuList,
                Records = menuList.Count()
            };
            return Ok(records);
        }

        /// <summary>
        /// 获取菜单信息
        /// </summary>
        [HttpGet]
        [Route("{id}")]
        public async Task<ActionResult<SysMenuDto>> Get([FromRoute]string id)
        {
            var menuDto = await _sysMenuService.FindAsync(id);
            return Ok(menuDto);
        }

        /// <summary>
        /// 修改菜单信息
        /// </summary>
        /// <param name="menuReq"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("edit")]
        public async Task<ActionResult<bool>> Edit([FromBody]MenuEditRequestDto menuReq)
        {
            if (!_canEditOrDeleteMenu)
            {
                throw new BusinessException("预览站点，未开启编辑功能");
            }
            menuReq.ParentId = menuReq.ParentId.IsBlank() ? string.Empty : menuReq.ParentId;
            menuReq.Remark = menuReq.Remark.IsBlank() ? string.Empty : menuReq.Remark;
            menuReq.Icon = menuReq.Icon.IsBlank() ? "right" : menuReq.Icon;
            await _menuService.UpdateAsync(menuReq);
            return Ok(true);
        }

        /// <summary>
        /// 批量删除菜单信息
        /// </summary>
        /// <param name="ids">id集合</param>
        /// <returns></returns>
        [HttpPost]
        [Route("delete")]
        public async Task<ActionResult<bool>> Delete([FromBody]IList<string> ids)
        {
            if (!_canEditOrDeleteMenu)
            {
                throw new BusinessException("预览站点，未开启删除功能");
            }
            await _sysMenuService.DeleteAsync(ids);
            return Ok(true);
        }

        /// <summary>
        /// 获取菜单树状结构
        /// </summary>
        [HttpGet]
        [Route("tree")]
        public async Task<ActionResult<IEnumerable<SelectTreeResponseDto>>> GetTree()
        {
            var menuList = await _menuService.GetMenuAsync(null, false, _currentUserService.IsSystemCompany());
            var treeList = menuList
                .OrderBy(x => x.ParentId)
                .OrderBy(x => x.Order)
                .Select(x => new SelectTreeResponseDto
                {
                    Id = x.Id,
                    PId = x.ParentId,
                    Value = x.Id,
                    Label = x.Name
                });
            return Ok(treeList);
        }

        /// <summary>
        /// 获取用户拥有的菜单树状结构
        /// </summary>
        [HttpGet]
        [Route("user-tree")]
        public async Task<ActionResult<List<TreeResponseDto>>> GetUserTree()
        {
            var menuList = await _menuService.GetMenuTreeAsync(true, _currentUserService.IsSystemCompany());
            return Ok(menuList);
        }
    }
}
